package org.example.modules.user.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.common.utils.ThreadLocalUtil;
import org.example.common.validator.Assert;
import org.example.modules.user.common.Commsult;
import org.example.modules.user.entry.SideJobDetails;
import org.example.modules.user.entry.SideJobMain;
import org.example.modules.user.entry.UserWallet;
import org.example.modules.user.entry.vo.JobFeedBackVo;
import org.example.modules.user.entry.vo.OrderRankVo;
import org.example.modules.user.entry.vo.SideJobDetailsVo;
import org.example.modules.user.entry.vo.SideJobMainVo;
import org.example.modules.user.mapper.SideJobDetailsMapper;
import org.example.modules.user.mapper.SideJobMainMapper;
import org.example.modules.user.mapper.UserMapper;
import org.example.modules.user.service.SideJobMainService;
import org.example.modules.user.service.UserWalletService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Description SideJobMainServiceImpl
 * @Author xiaotian
 * @Date 2025-04-17
 */
@Slf4j
@Service
public class SideJobMainServiceImpl extends ServiceImpl<SideJobMainMapper, SideJobMain> implements SideJobMainService {


    @Autowired
    private SideJobMainMapper sideJobMainMapper;

    @Autowired
    private SideJobDetailsMapper sideJobDetailsMapper;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<SideJobMainVo> getAllSideJob() {
        LambdaQueryWrapper<SideJobMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SideJobMain :: getCreateName, ThreadLocalUtil.getUserId());
        List<SideJobMain> sideJobMainList = sideJobMainMapper.selectList(lambdaQueryWrapper);
        List<SideJobMainVo> list = new ArrayList<>();
        for(SideJobMain sideJobMain1:sideJobMainList){
            SideJobMainVo sideJobVo = new SideJobMainVo();
            BeanUtils.copyProperties(sideJobMain1,sideJobVo);
            sideJobVo.setAcceptList(sideJobMainMapper.getAcceptList(sideJobMain1.getId()));
            list.add(sideJobVo);
        }
        return list;
    }
    @Transactional
    @Override
    public Integer saveSideJob(JSONObject data) {
        SideJobMain sideJobMain = data.toJavaObject(SideJobMain.class);
        sideJobMain.setCreateTime(LocalDateTime.now().toString());
        sideJobMain.setCreateName(ThreadLocalUtil.getUserId());
        sideJobMain.setGenderRequire(data.getInteger("gender"));
        sideJobMain.setStatus(1);
        sideJobMain.setRemainCount(sideJobMain.getCount());
        if(sideJobMain.getType().equals("1")||sideJobMain.getType().equals("2")){
           Integer flag =  userWalletService.orderPay(BigDecimal.valueOf(sideJobMain.getSolar()));
           if(flag==0){
               return 0;
           }
        }
        Integer Id = data.getInteger("Id");
        if(Id!=null){
            sideJobMain.setId(Id);
            sideJobMain.setCreateTime(LocalDateTime.now().toString());
            sideJobMainMapper.updateById(sideJobMain);
        }else{
            sideJobMainMapper.insert(sideJobMain);
        }
        return 1;
    }

    @Override
    public List<SideJobMainVo> getSideJob(JSONObject data) {
        Integer type = data.getInteger("SubTabType");
        Integer topType = data.getInteger("TopTabType");
        LambdaQueryWrapper<SideJobMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<SideJobMain> sideJobMainList = new ArrayList<>();
        if(topType==1){
            lambdaQueryWrapper.eq(SideJobMain :: getCreateName,ThreadLocalUtil.getUserId());
        }
        if(topType==2){
            List<Integer> IdList = sideJobDetailsMapper.selectIdList(ThreadLocalUtil.getUserId());
            lambdaQueryWrapper.in(SideJobMain :: getId,IdList);
        }
        if(topType==3){
            lambdaQueryWrapper.eq(SideJobMain :: getStatus, 1);
        }
        if(type!=0){
            lambdaQueryWrapper.eq(SideJobMain :: getType,type);
        }
        lambdaQueryWrapper.orderByDesc(SideJobMain::getCreateTime);
        sideJobMainList = sideJobMainMapper.selectList(lambdaQueryWrapper);
        List<SideJobMainVo> list = new ArrayList<>();
        for(SideJobMain sideJobMain1:sideJobMainList){
            SideJobMainVo sideJobVo = new SideJobMainVo();
            BeanUtils.copyProperties(sideJobMain1,sideJobVo);
            sideJobVo.setAcceptList(sideJobMainMapper.getAcceptList(sideJobMain1.getId()));
            list.add(sideJobVo);
        }
        return list;
    }

    @Override
    public SideJobMainVo getSideJobDetails(JSONObject data) {
        Integer Id = data.getInteger("Id");
        SideJobMain sideJobMain = sideJobMainMapper.getSideJobDetails(Id);
        SideJobMainVo sideJobVo = new SideJobMainVo();
        BeanUtils.copyProperties(sideJobMain,sideJobVo);
        sideJobVo.setCreateNameImage(userMapper.selectUser(sideJobMain.getCreateName()).getAvatarUrl());
        sideJobVo.setAcceptList(sideJobMainMapper.getAcceptList(sideJobMain.getId()));
        return sideJobVo;
    }

    @Override
    @Transactional
    public Commsult accpetJob(JSONObject data) throws Exception {
        Integer Id = data.getInteger("Id");
        Integer type = data.getInteger("type");
        SideJobMain sideJobMain = sideJobMainMapper.selectById(Id);
        List<SideJobDetailsVo> sideJobDetailsList = new ArrayList<>();
        sideJobDetailsList = sideJobMainMapper.getAcceptList(Id);
        if(type==1){
            if(sideJobMain.getCreateName().equals(ThreadLocalUtil.getUserId())){
                return Commsult.fail("不能接自己发布的订单");
            }
            if(sideJobMain.getStatus()!=null&&sideJobMain.getStatus()!=1){
                return Commsult.fail("该订单已被接取");
            }

            String accpetTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String accpetName = ThreadLocalUtil.getUserId();
            int count = sideJobMain.getRemainCount()-1;
            if(count<0){
                return Commsult.fail("该订单已被接完");
            }

            for(SideJobDetailsVo sideJobDetails:sideJobDetailsList){
                if(sideJobDetails.getAcceptName().equals(accpetName)){
                    return Commsult.fail("不能重复接取");
                }
            }
            sideJobMainMapper.accpetJob(Id,count);
            SideJobDetails sideJobDetails = new SideJobDetails();
            sideJobDetails.setOrderId(String.valueOf(Id));
            sideJobDetails.setAcceptName(accpetName);
            sideJobDetails.setCreateName(sideJobMain.getCreateName());
            sideJobDetails.setTime(accpetTime);
            sideJobDetails.setStatus(2);
            if(sideJobMain.getType().equals("1")||sideJobMain.getType().equals("2")){
                sideJobDetails.setUpdateTime(accpetTime);
            }
            sideJobDetailsMapper.insert(sideJobDetails);
        }else{
            if(type==0){
                for(SideJobDetailsVo sideJobDetails : sideJobDetailsList){
                    if(sideJobDetails.getStatus()!=0){
                        return Commsult.fail("该兼职已被接取无法撤回");
                    }
                }
            }
            sideJobMainMapper.updateCancel(Id,type);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("amount",sideJobMain.getSolar());
            jsonObject.put("accountType","back");
            userWalletService.recharge(jsonObject);
        }


        return  Commsult.success(null);
    }

    @Override
    public List<OrderRankVo> getOrderRank() {
        List<OrderRankVo> sideJobMainList = sideJobMainMapper.getOrderRankInfo();
        sideJobMainList.sort(Comparator.comparing(OrderRankVo::getAmount).reversed());
        return sideJobMainList;
    }

    @Override
    public List<JobFeedBackVo> getJobFeedback() {
        List<JobFeedBackVo> strList = sideJobMainMapper.getJobFeedBackList(ThreadLocalUtil.getUserId());
        log.info("list:{}",strList);
        return strList;
    }

    @Override
    public SideJobMain getJobDetailsById(Integer orderId) {

        return sideJobMainMapper.selectById(orderId);
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void status(){
        sideJobMainMapper.updateSus();
    }
}
